<template>
	<div id="Favourite">
		<el-container>
			<el-header style="height: 55px;">
				<span style="padding-left: 50px; float: left; color: bisque; font-size: 40px; margin-top: 10px;">
					百&nbsp;货&nbsp;商&nbsp;城</span>
				<ul>
					<li>
						<div class="userImg">
							<el-avatar style="margin-top: 10px;" icon="el-icon-s-custom"></el-avatar>
							<!-- 把用户名传递过来 -->
							<span v-if="username">欢迎{{username}}</span>
							<span v-else style="color: skyblue;">
								<router-link to="/MemberLogin">去登录</router-link>
							</span>
						</div>
					</li>
					<li @click='changePage("Index")'>商城首页</li>
					<li @click='changePage("ShopCart")'>购物车</li>
					<li style="color: red;" @click='changePage("Favorites")'>收藏夹</li>
          <li @click='changePage("OrderCenter")'>我的订单</li>
					<li @click='changePage("PerCenter")'>个人中心</li>
					<li v-if="username" @click='changePage("exit")'>退出登录</li>
					<li style="color: greenyellow ; font-size: 22px;" @click='changePage("main")'>管理员入口</li>
				</ul>
			</el-header>
			<el-main>
				<div>
					<p>
						<input type="search" name="" id="" value="" placeholder="请输入搜索内容" />
						<el-button type="primary" icon="el-icon-search">搜索</el-button>
					</p>
					<el-table class="" ref="buyerTable" border stripe
						:data="cartList.slice((currentPage-1)*pageSize,currentPage*pageSize)" tooltip-effect="dark"
						style="width: 100%" height="520" border @selection-change="handleSelectionChange"
						:row-key="getkey">
						<el-table-column type="selection" width="55" :reserve-selection="true">
						</el-table-column>

						</el-table-column>
						<el-table-column label="商品名称" prop="goods_name" width="150" align="center" />
						<el-table-column label="图片" width="100" align="center">
							<template slot-scope="scope">
								<el-popover placement="right" trigger="hover">
									<el-image slot="reference" :src="scope.row.goods_small_logo" width="80" height="80"
										@click="getImgUrl(scope.row.goods_small_logo)" />
									<el-image style="width: 250px; height: 250px" :src="scope.row.goods_small_logo"
										fit="cover" />
								</el-popover>
							</template>
						</el-table-column>
						<el-table-column label="商品简介" prop="goods_introduce" />
						<el-table-column label="单价" prop="goods_price" width="190" header-align="center" align="center">
							<template slot-scope="scope">
								<div>￥{{ scope.row.goods_price }}</div>
							</template>
						</el-table-column>
						<el-table-column label="收藏时间" prop="collection_time" width="200" align="center" />

						<el-table-column label="操作" width="200" align="center">
							<template slot-scope="scope">
								<el-tooltip class="item" effect="dark" content="加购物车" placement="top">
									<el-button size="mini" type="success" icon="el-icon-goods"
										@click="addShopCart(scope.row.goods_id)" />
								</el-tooltip>
								<el-tooltip class="item" effect="dark" content="删除" placement="top">
									<el-button size="mini" type="danger" icon="el-icon-delete"
                  @click="deleteFavoriteGoods(scope.row)" />
								</el-tooltip>
							</template>
						</el-table-column>
					</el-table>
					<div class="cart-option">
						<el-button type="danger" @click="batchDeleteFavoriteGoods">删除选中商品</el-button>
					</div>
					<!-- 分页器 -->
					<div class="block" style="margin-top:15px;">
						<el-pagination align='center' @size-change="handleSizeChange"
							@current-change="handleCurrentChange" :current-page="currentPage"
							:page-sizes="[1,5,10,20,50,100]" :page-size="pageSize"
							layout="total, sizes, prev, pager, next, jumper" :total="cartList.length">
						</el-pagination>
					</div>
				</div>
			</el-main>
		</el-container>
	</div>
</template>
<script>
	export default {
		mounted() {
			//this.getCollectionByMemberId();
		},
		created: function() {

			//来到Favorites页面首先看看有误登录的用户信息
			let memberInfo = window.sessionStorage.getItem("memberInfo");
			if (memberInfo) {
				let memberInfoObj = JSON.parse(memberInfo);
				//console.log('memberInfoObj',memberInfoObj)
				this.username = memberInfoObj.username;
				this.memberId = memberInfoObj.member_id;
				this.getCollectionByMemberId();
			} else {
				this.$notify({
					title: '提示',
					message: "请先登录",
					duration: 2000
				});
				this.$router.push('/MemberLogin');
			}

			//this.total = this.tableData.length;
		},
		data() {
			return {
				cartList: [],
				selectGoodsList: [],
				multipleSelection: [],
				select_lines: 0,
				currentPage: 1, // 当前页码
				total: 20, // 总条数
				pageSize: 5, // 每页的数据条数
				activeIndex: '1',

				username: '',
				memberId: ''

			}
		},
		methods: {
      batchRemoveFavoriteItemByIdArray: async function(itemIdArray) {
      	console.log('itemIdArray', itemIdArray)
      	let _this = this;
      	let url = "/api/mall/CollectionServlet?method=removeFavoritemArrayById";
      	let idArrayStr = itemIdArray.join(',')
      	await this.$http.get(url, {
      		params: {
      			idArrayStr: idArrayStr,
      		}
      	}).then(function(response) {
      		console.log("address服务端返回的数据为:", response);
      		if (response.data.code == 0) {
      			_this.$message(response.data.msg)
      			console.log("11111")
      			_this.multipleSelection = [];
      			_this.getCollectionByMemberId(_this.member_id);
      		} else {
      			_this.$message(response.data.msg)
      		}

      	}).catch(function(error) {
      		console.log("服务端产生异常为:", error);
      		_this.$notify({
      			title: '提示',
      			message: "系统错误:" + error,
      			duration: 2000
      		});

      	})
      },
      // 批量删除购物车商品
      batchDeleteFavoriteGoods() {
      	if (this.multipleSelection.length > 0) {} else {
      		return this.$message.error('请勾选要移除购物车的商品')
      	}
        let arr = [];
      	for (let i = 0; i < this.multipleSelection.length; i++) {
      		arr.push(this.multipleSelection[i].collection_id);
      	}

      	this.$confirm('此操作将移除勾选的购物车的商品, 是否继续?', '提示', {
      		confirmButtonText: '确定',
      		cancelButtonText: '取消',
      		type: 'warning'
      	}).then(async () => {
      		console.log(55555555555555555555)
      		//console.log('aaaaaaaaaaaaaaaaaaaarr',arr);
      		this.batchRemoveFavoriteItemByIdArray(arr);

      	}).catch((e) => {
      		console.log(e)
      		this.$message.info('已取消删除')
      	})
      },
      removeFavoriteItemById: async function(itemId) {
      	console.log('itemId', itemId)
      	let _this = this;
      	let url = "/api/mall/CollectionServlet?method=removeFavoriteById";

      	await this.$http.get(url, {
      		params: {
      			itemId: itemId,
      		}
      	}).then(function(response) {
      		console.log("address服务端返回的数据为:", response);
      		if (response.data.code == 0) {
      			_this.$message(response.data.msg)
      			for (var i = 0; i < _this.cartList.length; i++) {
      				if (_this.cartList[i].collection_id == itemId) {
      					//数据库操作成功后前台删除
      					_this.cartList.splice(i, 1);
      					return;
      				}
      			}
      		} else {
      			_this.$message(response.data.msg)
      		}

      	}).catch(function(error) {
      		console.log("服务端产生异常为:", error);
      		_this.$notify({
      			title: '提示',
      			message: "系统错误:" + error,
      			duration: 2000
      		});

      	})
      },
	  //在收藏夹中可以选择加入购物车
	  async addShopCart(goodsId) {
	  	console.log("Favorite页面 addShopCart被执行")
	  	let _this = this;
	  	let url = "/api/mall/ShopCartServlet?method=addCartGoodsById";
	  
	  	await this.$http.get(url, {
	  		params: {
	  			goodsId: goodsId,
	  			memberId: _this.memberId
	  		}
	  	}).then(function(response) {
	  		console.log("addCartGoodsById 服务端返回的数据为:", response);
	  		if (response.data.code == 0) {
	  			_this.$message.success(response.data.msg)
	  		} else {
	  			_this.$message(response.data.msg)
	  		}
	  
	  	}).catch(function(error) {
	  		console.log("服务端产生异常为:", error);
	  		_this.$notify({
	  			title: '提示',
	  			message: "系统错误:" + error,
	  			duration: 2000
	  		});
	  
	  	})
	  
	  },
      // 删除单个商品
      deleteFavoriteGoods(row) {
      	this.$confirm('此操作将移除购物车的商品, 是否继续?', '提示', {
      		confirmButtonText: '确定',
      		cancelButtonText: '取消',
      		type: 'warning'
      	}).then(async () => {
      		this.removeFavoriteItemById(row.collection_id);
      	}).catch((e) => {
      		console.log(e)
      		this.$message.info('已取消删除')
      	})
      },
			getCollectionByMemberId: async function() {
				let _this = this;
				let url = "/api/mall/CollectionServlet?method=getCollectionByMemberId";

				await this.$http.get(url, {
					params: {
						memberId: this.memberId,
					}
				}).then(function(response) {
					if (response.data.code == 0) {
						let CollectionList = response.data.data; //.itemGoods
						_this.cartList = [];
						for (let i = 0; i < CollectionList.length; i++) {
							let temp = CollectionList[i].itemGoods;
							//console.log('temp',temp)
							if (temp) {
								temp.collection_id = CollectionList[i].collection_id;
								temp.collection_time = CollectionList[i].collection_time;
								_this.cartList.push(temp);
							}
						}

					} else {
						_this.$message(response.data.msg)
					}

				}).catch(function(error) {
					console.log("服务端产生异常为:", error);
					_this.$notify({
						title: '提示',
						message: "系统错误:" + error,
						duration: 2000
					});

				})
			},
			//解决触发两次handleSelectionChange
			getkey(row) {
				//row.id的id必须存在并且是唯一的值
				return row.collection_id;
				console.log(row.id);
			},
			//select change
			handleSelectionChange(val) {
				this.multipleSelection = val;
				// this.selectGoodsList = val;
				// this.select_lines = this.multipleSelection.length;
				console.log(this.multipleSelection.length);
			},

			// 清空选择的值
			clearSelect() {
				this.$refs.buyerTable.clearSelection()
			},

			//改变每页显示记录的条数
			handleSizeChange(val) {
				console.log(`每页 ${val} 条`);
				this.currentPage = 1;
				this.pageSize = val;
			},
			handleCurrentChange(val) {
				console.log(`当前页: ${val}`);
				this.currentPage = val;
			},

			//编辑按钮
			handleEdit(index, row) {
				console.log(index, row);
			},

			//删除按钮
			handleDelete(index, row) {
				console.log(index, row);
			},
			//获取图片路径
			getImgUrl(row) {
				console.log(row);
				// console.log(row.img);
				// return row.img;
			},
			//页面跳转事件
			changePage(path) {
				window.sessionStorage.setItem('activePath', '/' + path)
				if (path == "exit") {
					window.sessionStorage.removeItem("memberInfo")
					path ="MemberLogin"
					window.sessionStorage.setItem('activePath', '/' + path)
				}
				this.$router.push('/' + path);

			},
			tableRowClassName({
				row,
				rowIndex
			}) {
				if (rowIndex === 0) {
					return 'th';
				}
				return '';
			},
			switchChange() {
				this.istag = !this.istag;

			},

			current_change: function(currentPage) {
				this.currentPage = currentPage;
			},

			// 获取购物车列表（这个要在created里面调用）
			async getCartList() {
				const {
					data: res
				} = await this.$http.get(getCartListUrl)
				if (res.code !== 200) return this.$message.error(res.msg)
				this.cartList = res.data.list
				this.cartList.forEach(item => {
					// 因为后台接口返回的商品SKU是对象的格式，我们取它的值，然后重新赋值使用
					if (item.skuJson) {
						item.sku = []
						for (let i in item.skuJson) {
							item.sku.push(item.skuJson[i])
						}
						item.sku = item.sku.join('，')
					}
				})
			},
			// 购物车选择事件（elemenUI表格勾选保存的值）
			cartSelectionChange(val) {
				this.multipleSelection = val;

			},
			// 商品数量文本框改变事件
			cartGoodsAmountChange(e, orderInfo) {
				if (e.target.value <= 0) {
					orderInfo.amount = 1
					return this.$message.error('商品数量不能小于0')
				}
			},
			// 商品数量加1
			addAmountCount(orderInfo) {
				++orderInfo.amount
			},
			// 商品数量减1
			subtractAmountCount(orderInfo) {
				if (orderInfo.amount <= 1) {
					return this.$message.error('商品数量不能小于0')
				}
				--orderInfo.amount
			},

			handleSelect(key, keyPath) {
				console.log(key, keyPath);
			}
		},
		computed: { //存在缓存，建议不经常的变化的在次操作
			//计算总价
			cartTotalPrice() {
				let sum = 0
				this.multipleSelection.forEach(item => {
					sum += item.price * item.amount
				})
				// 因为要保留小数点后面两位，所以要toFixed(2)
				return sum.toFixed(2);
				// return 0.0;
			},
		}
	}
</script>

<style scoped>
	* {
		box-sizing: border-box;
		margin: 0;
		padding: 0;
	}

	#Favourite {
		position: absolute;
		display: flex;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		/* background-color: #FF0000; */
	}

	.el-header {
		background-color: #cccccc;
		color: #333;
		text-align: center;
		height: 5%;
		line-height: 25px;
	}

	.el-main {
		/* background-color: #00ffff; */
		text-align: center;
		width: 100%;
		height: 95%;
	}

	.el-main>div {
		width: 70%;
		margin: 0px auto;
		padding-top: 20px;
		/* background-color: #0000FF; */
	}

	.el-container {
		width: 100%;
		height: 100%;
		padding: 0;
		margin: 0;
	}

	.el-header>ul {
		position: absolute;
		right: 5px;
	}

	.el-header>ul>li {
		float: left;
		list-style: none;
		margin: 5px;
		user-select: none;
	}

	.el-header>ul>li:not(:first-child):hover {
		color: red;
		text-decoration: underline;
	}

	.el-avatar {
		position: absolute;
		left: -30px;
		top: 2px;
		width: 33px;
		height: 30px;
		color: #42B983;
		/* border: 1px solid #0000FF; */
	}

	.el-avatar--icon {
		font-size: 35px;
	}

	input[type="search"] {
		width: 600px;
		height: 35px;
		font-size: 15px;
		outline: none;
		border: 2px solid #0000FF;
		border-radius: 5px;
	}

	.el-main>div>p>.el-button {
		width: 60px;
		height: 35px;
		font-size: 15px;
		margin-bottom: 20px;
	}

	.item {
		width: 50px;
		height: 30px;
	}

	.cart-option {
		position: relative;
		height: 31px;
		/* font-size: 50px; */
		background-color: #c3c3c3;
		border: 1px solid transparent;
	}

	.cart-option>.el-button {
		position: absolute;
		left: 5px;
		top: 2px;
		height: 25px;
		line-height: 25px;
	}

	ul>li {
		font-size: 20px;
		padding: 10px;
	}
</style>
